<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import html2canvas from "html2canvas";

import StarsOne from "../components/starsOne.vue";
import StarsTwo from "../components/starsTwo.vue";
import StarsThree from "../components/starsThree.vue";
import StarsFour from "../components/starsFour.vue";
import StarsFive from "../components/starsFive.vue";
import starsUnknownVue from "../components/starsUnknown.vue";

//获取dom元素
let imageDom = ref();

//图片文件
let cardImg = ref("");

//图片名称值记录 用于查询图片结果
let imgName = ref("");

//接口获取到的结果集合
let words = ref([""]);

//接口获取到的星级
let starNum = ref(0);

//模态库是否展示
let modelIsShow = ref(false);

//是否显示公众号相关信息

//设置公用状态,判断是否能够跳出循环
let statu = ref(true);

//是否显示加载状态
let loadingIsShow = ref(false);

//dom挂载钩子函数
onMounted(() => {});

//文件上传
function upload(base64: string, imgName: string): void {
  let formData = {
    //图片
    img_data: base64,
    //图片名
    img_name: imgName,
    //上传类型
    infer_id: "10",
    //用户名为图片名
    user_id: imgName,
  };
  loadingIsShow.value = true;
  const doUpload = new Request("http://www.expertstree.com/upload_img.html", {
    method: "POST",
    body: JSON.stringify(formData),
  });
  fetch(doUpload)
    .then((response) => response.json())
    .then((data) => {
      //上传成功
      console.log("上传成功：" + data);
      if (JSON.parse(data).err_msg == "ok") {
        //循环请求后台结果
        let Interval = setInterval(() => {
          if (!statu.value) {
            clearInterval(Interval);
            return;
          }
          getResult(formData.img_name);
        }, 5000);
      } else {
        // 新增异常状态处理，显示未知页面
        words.value.push("你太神秘，我们AI读不出~");
        starNum.value = 6;
        statu.value = false;
        return;
      }
    })
    .catch((err) => {
      alert(err);
    });
}

//获取上传dom元素
let uploadInput = ref();

//手动触发点击上传事件
function clickUpload(): void {
  uploadInput.value.click();
}

//input修改后触发函数，获取文件
function doInputImg(): void {
  let file = uploadInput.value.files[0];
  //文件名+时间戳+文件名组合
  let dataFileName =
    file.name.split(".")[0] + "_" + new Date().getTime() + "_" + file.name;
  imgName.value = dataFileName;

  //data64文件
  let file64: string;
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function (e: any) {
    file64 = e.target.result;
    upload(file64, dataFileName);
  };
}

// 查询结果
function getResult(imgName: string) {
  let data = {
    img_name: imgName,
    infer_id: "8",
    user_id: imgName.split("_")[0],
  };
  const getResult = new Request("http://www.expertstree.com/gam_qry.html", {
    method: "POST",
    body: JSON.stringify(data),
  });
  //查询结果出来以后，显示出词云
  fetch(getResult)
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      let jsonData = JSON.parse(data);
      let datas = jsonData.虎年关键词.split("|");
      starNum.value = datas[0];
      console.log(starNum.value);
      words.value = datas[1].split("，");
      console.log("获取到的数据集合为：" + JSON.stringify(words.value));
      if (jsonData.infer_status == 1) {
        statu.value = false;
      }
    })
    .catch((err) => {
      console.log(err);
      words.value.push("你太神秘，我们AI读不出~");
      starNum.value = 6;
    });
}

//生成图片
function generatePicture() {
  html2canvas(imageDom.value).then((img) => {
    // 转成图片，生成图片地址(如需将图片转为file 文件，请自行处理)
    let imgUrl = img.toDataURL("image/png"); //可将 canvas 转为 base64 格式
    cardImg.value = img.toDataURL("image/png");
    modelIsShow.value = true;
    console.log(imgUrl);
    // getImageForBase64("测试报告", imgUrl);
  });
}

//计算属性 获取描述颜色颜色
let colorClass = computed(() => {
  let colors = ["one", "two", "three", "four", "five"];
  return colors[starNum.value - 1];
});
</script>

<template>
  <div class="page2">
    <div class="user_info" ref="imageDom">
      <div v-show="!statu">
        <StarsOne v-if="starNum == 1" />
        <StarsTwo v-if="starNum == 2" />
        <StarsThree v-if="starNum == 3" />
        <StarsFour v-if="starNum == 4" />
        <StarsFive v-if="starNum == 5" />
        <starsUnknownVue v-if="starNum == 6" />
      </div>
      <div class="desc" :class="colorClass" v-show="!statu">
        <p v-for="(item, index) in words" :key="index">{{ item }}</p>
      </div>
    </div>
    <div class="btns" v-show="!statu">
      <div class="btn" onclick="location.reload()">再来一次</div>
      <div class="btn" @click="generatePicture()">保存分享</div>
    </div>
    <div class="upload" @click="clickUpload()" v-if="statu">
      <div class="upload_card" v-if="!loadingIsShow">
        <img src="../assets/imgs/shangchuan.png" alt="" />
        <p>点击上传</p>
        <input
          type="file"
          title="上传小于1M的文件"
          ref="uploadInput"
          class="uploadInput"
          @change="doInputImg()"
        />
      </div>
      <div class="loading" v-if="loadingIsShow">
        <img src="../assets/imgs/loading.png" />
        正在分析
      </div>
    </div>

    <div class="modals" :class="modelIsShow ? 'showModals' : 'hideModals'">
      <img :src="cardImg" class="modals-img-card" alt="" />
      <div class="btn cardImg-close" @click="modelIsShow = false">关闭</div>
    </div>
  </div>
</template>

<style scoped>
@font-face {
    font-family: 'STXINWEI';
    src: url('../assets/fonts/STXINWEI.TTF');
    font-weight: normal;
    font-style: normal;
}
.page2 {
  background-color: rgb(242, 242, 242);
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-content: space-around;
  justify-content: space-around;
}
.stars {
  width: 100%;
}
.btns {
  width: 100%;
  display: flex;
  justify-content: space-around;
  top: 85%;
}
.btn {
  height: 30px;
  width: 100px;
  text-align: center;
  background-color: rgb(234, 159, 96);
  margin: 1rem;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0.3rem;
  color: #363636;
  font-weight: 500;
}
.desc p {
  margin: 10px 0;
  text-align: center;
  font-size: 1.5rem;
  font-family: STXINWEI;
}
.upload {
  width: 90%;
  height: 300px;
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 10px;
  position: absolute;
  left: 5%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload img {
  width: 5rem;
}

.user_info {
  background-color: rgb(242, 242, 242);
  padding-bottom: 40px;
  min-height: 60px;
}
.uploadInput {
  display: none;
}
.loading {
  width: 100px;
  height: 100px;
  text-align: center;
}

.loading img {
  width: 60px;
  margin: 20px;
  animation: rotateImg linear 1.5s infinite;
}
@keyframes rotateImg {
  from {
    transform: rotateZ(0deg);
  }
  to {
    transform: rotateZ(360deg);
  }
}
.gzh {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 0.9rem;
  margin-top: 20px;
}
.gzh img {
  width: 100px;
  margin-right: 5px;
}

.modals {
  width: 100%;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
.showModals {
  z-index: 10;
}
.hideModals {
  z-index: -10;
}
.modals-img-card {
  width: 80%;
}

.one {
  color: rgb(46, 54, 99);
}

.two {
  color: rgb(102, 18, 6);
}
.three {
  color: rgb(78, 82, 115);
}
.four {
  color: rgb(170, 101, 0);
}
.five {
  color: rgb(237, 125, 49);
}
</style>
